package com.macro.mall.demo.design.pattern.template;

import cn.hutool.json.JSONUtil;
import com.macro.mall.common.exception.MallCommonException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * 通用业务处理模板
 */
public class BizProcessTemplate {

    private static final Logger LOGGER = LoggerFactory.getLogger(BizProcessTemplate.class);
    public static <Response extends Result, Request, Model> Response process(Request request, BizProcessTemplateCallback<Response, Request, Model> callback) {

        long startTime = System.currentTimeMillis();

        // 1.初始化
        Response response = null;
        Model model = null;
        String bizSceneCode = null;
        try {
            // 2.初始化业务类型
            bizSceneCode = callback.getBizSceneCode() == null ? "COMMON": callback.getBizSceneCode();
            LOGGER.info("service start, request:{}", JSONUtil.toJsonStr(request));
            // 3.校验入参
            callback.checkParam(request);
            // 4.执行业务逻辑
            model = callback.bizProcess(request);
            // 5.构建响应
            response = callback.buildResponse(model);

        }
//        catch (MallBizException e) {
//            // 7.业务异常处理
//            callback.exceptionProcess(request);
//        }
//        catch (MallSystemException e) {
//            // 8.系统异常处理
//            callback.exceptionProcess(request);
//        }
//        catch (MallUnknownException e) {
//            // 9.未知异常处理
//            callback.exceptionProcess(request);
//        }
        catch (Throwable e) {
            // 10.最终未知异常处理
            callback.exceptionProcess(request);
        } finally {
            // 11.执行 Finally 处理
            callback.finallyProcess(request, response);
            LOGGER.info("service end, response:{}, cost:{}ms", JSONUtil.toJsonStr(response), System.currentTimeMillis() - startTime);
        }

        return response;
    }
}
